﻿using System;
using System.Threading;
using QQ2564874169.Core.Utils;

namespace QQ2564874169.Core.Lock
{
    /// <summary>
    /// 队列锁。
    /// </summary>
    public class QueueLockspace : ILockspace
    {
        /// <summary>
        /// 全局超时时间（秒）
        /// </summary>
        public static int? Timeout { get; set; }
        private ILocker _locker;
        private string _key;

        static QueueLockspace()
        {
            Timeout = 60;
        }

        public QueueLockspace(ILocker locker, string key, int? timeout = null)
        {
            if (locker == null)
                throw new ArgumentNullException(nameof(locker));
            if (string.IsNullOrEmpty(key))
                throw new ArgumentNullException(nameof(key));

            _locker = locker;
            _key = key;

            DateTime? t = null;

            if (timeout.HasValue)
            {
                t = DateTime.Now.AddSeconds(timeout.Value);
            }
            else if (Timeout.HasValue)
            {
                t = DateTime.Now.AddSeconds(Timeout.Value);
            }

            while (_locker.Lock(key) == false)
            {
                if (t != null && t < DateTime.Now)
                {
                    throw new TimeoutException(key);
                }
                TaskHelper.Delay(10).Wait();
            }
        }

        public void Dispose()
        {
            _locker.UnLock(_key);
            _locker = null;
            _key = null;
        }
    }
}
